<template>
  <div class="employee-edit">
    <a-card :title="`编辑员工 - ${formState.name || ''}`">
      <template #extra>
        <a-button @click="goBack">取消</a-button>
      </template>

      <a-form
          :model="formState"
          :rules="formRules"
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 14 }"
          @finish="handleSubmit"
      >
        <a-form-item label="姓名" name="name">
          <a-input v-model:value="formState.name" />
        </a-form-item>

        <a-form-item label="工号" name="employeeId">
          <a-input v-model:value="formState.employeeId" disabled />
        </a-form-item>

        <a-form-item label="性别" name="gender">
          <a-radio-group v-model:value="formState.gender">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="2">女</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="部门" name="department">
          <a-input v-model:value="formState.department" />
        </a-form-item>

        <a-form-item label="职位" name="position">
          <a-input v-model:value="formState.position" />
        </a-form-item>

        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status">
            <a-select-option value="1">在职</a-select-option>
            <a-select-option value="2">离职</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="手机号" name="phone">
          <a-input v-model:value="formState.phone" />
        </a-form-item>

        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" />
        </a-form-item>

        <a-form-item label="入职日期" name="hireDate">
          <a-date-picker
              v-model:value="formState.hireDate"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </a-form-item>

        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="formState.remark" :rows="4" />
        </a-form-item>

        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" html-type="submit" :loading="loading">保存</a-button>
          <a-button style="margin-left: 10px" @click="resetForm">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { getEmployeeDetail, updateEmployee } from '@/api/employee'

const route = useRoute()
const router = useRouter()
const loading = ref(false)

// 表单数据 - 确保包含所有必要字段
const formState = ref({
  id: '',
  name: '',
  employeeId: '',
  gender: 1,
  department: '',
  position: '',
  status: '1',
  phone: '',
  email: '',
  hireDate: '',
  remark: ''
})

// 获取员工详情
const fetchEmployeeDetail = async () => {
  loading.value = true
  try {
    console.log('正在获取编辑员工ID:', route.params.id) // 调试日志
    const res = (await getEmployeeDetail(route.params.id)).data.data.list[route.params.id-1]
    console.log('编辑页获取的数据:', res) // 调试日志

    if (!res.id) {
      throw new Error('返回数据缺少ID字段')
    }

    formState.value = {
      ...res,
      status: res.status.toString() // 确保状态是字符串
    }
  } catch (error) {
    console.error('获取编辑数据失败:', error)
    message.error(`获取数据失败: ${error.message}`)
    router.push('/employee/list')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formState.value.id) {
    message.error('无效的员工ID')
    return
  }

  try {
    loading.value = true
    console.log('正在提交数据:', formState.value) // 调试日志

    const res = await updateEmployee(formState.value)
    console.log('更新响应:', res) // 调试日志

    message.success('员工信息更新成功')
    router.push(`/employee/detail/${formState.value.id}`)
  } catch (error) {
    console.error('更新失败:', {
      message: error.message,
      response: error.response?.data,
      stack: error.stack
    })
    message.error(`更新失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (!route.params.id) {
    message.error('缺少员工ID参数')
    router.push('/employee/list')
    return
  }
  fetchEmployeeDetail()
})
</script>

<style scoped>
.employee-edit {
  padding: 20px;
}
</style>